package extend;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * 易变业务使用脚本语言编写(编写高质量代码 改善Java程序的151个建议 p25)
 * 
 * @author wangbiao
 * @version 1.0 date 2013-9-13 下午3:19:34
 */

public class ScriptEngineTest {

	public static void main(String[] args) throws FileNotFoundException {
		// 获得一个JavaScript的执行引擎
		ScriptEngine engine = new ScriptEngineManager()
				.getEngineByName("javascript");
		// 建立上下文变量
		Bindings binding = engine.createBindings();
		binding.put("factor", 1);
		// 绑定上下文，作用域是当前引擎范围
		engine.setBindings(binding, ScriptContext.ENGINE_SCOPE);
		Scanner input = new Scanner(new FileInputStream("d:/model.txt"));
		while (input.hasNextInt()) {
			int first = input.nextInt();
			int sec = input.nextInt();
			System.out.println("输入的参数是" + first + "," + sec);
			// 执行js代码
			try {
				engine.eval(new FileReader("d:/model.js"));
				// 是否可调用方法
				if (engine instanceof Invocable) {
					Invocable in = (Invocable) engine;
					// 执行js中的函数
					Double result = (Double) in.invokeFunction("formula",
							first, sec);
					System.out.println("运算的结果 ： " +result.intValue());
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (ScriptException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
	}
}
